﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace sy2_12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private double getPacket(ref double total, int n)
        {
            if (n == 1)
                return total; // 最后一个红包分配剩余所有金额

            Random rand = new Random(Guid.NewGuid().GetHashCode());
            double avg = total / n; // 平均值
            // 生成在 avg上下浮动50%范围内的随机数
            double thisPacket = avg * rand.Next(50, 151) / 100;
            thisPacket = Math.Round(thisPacket, 2); // 保留两位小数
            total = Math.Round(total - thisPacket, 2); // 更新剩余金额
            return thisPacket;
        }

        // 计算红包总和
        private double sumPacket(double[] a)
        {
            double sum = 0;
            foreach (double num in a)
                sum += num;
            return Math.Round(sum, 2);
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取用户输入                
                double total = double.Parse(textBox1.Text);
                int n = int.Parse(textBox2.Text);
                // 验证输入                
                if (total <= 0 || n <= 0)
                {
                    MessageBox.Show("金额和个数必须大于0");
                    return;
                }
                double remaining = total;
                double[] redPackets = new double[n];
                // 生成所有红包                
                for (int i = n - 1; i >= 0; i--)
                {
                    redPackets[i] = getPacket(ref remaining, i + 1);
                }
                // 显示红包                
                textBox3.Text = string.Join(Environment.NewLine, redPackets);
                // 显示总和                
                textBox4.Text = sumPacket(redPackets).ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("输入错误: " + ex.Message);
            }
        }
    }
}
